package cn.stylefeng.guns.modular.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.modular.entity.Frame;
import cn.stylefeng.guns.modular.entity.Frameitem;
import cn.stylefeng.guns.modular.entity.Schedule;
import cn.stylefeng.guns.modular.service.FrameService;
import cn.stylefeng.guns.modular.service.FrameitemService;
import cn.stylefeng.guns.modular.service.ScheduleIndexService;
import cn.stylefeng.guns.modular.service.ScheduleitemService;
import cn.stylefeng.guns.modular.warpper.ScheduleWrapper;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.omg.PortableInterceptor.SUCCESSFUL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 日程控制器
 */
@Controller
@RequestMapping("/schedule")
public class ScheduleIndexController extends BaseController {

    private static String PREFIX = "/schedule";



    @Autowired
    public ScheduleIndexService scheduleIndexService;
    @Autowired
    public ScheduleitemService scheduleitemService;
    @Autowired
    public FrameService frameService;
    @Autowired
    public FrameitemService frameitemService;


    /**
     * 跳转到日程首页
     * @return
     */
    @RequestMapping("/index")
    public String index(){
        return "/console_schedule_index.html";
    }

    /**
     * 跳转到日程
     * @return
     */
    @RequestMapping("")
    public String richeng(){
        return this.PREFIX+"/schedule.html";
    }

    /**
     * 跳转到日程详情
     * @param scheduleId ：日程id
     * @return
     */
    @RequestMapping("/details")
    public String scheduleDetails(@RequestParam Long scheduleId){
        return this.PREFIX+"/schedule_details.html";
    }

//    @RequestMapping("/details")
//    public String scheduleDetails(@RequestParam Long scheduleId,
//                                  @RequestParam Long frameId){
//        return this.PREFIX+"/schedule_details.html";
//    }


    /**
     * 跳转到创建日程界面
     * @return
     */
    @RequestMapping("/create")
    public String create(){
        return  this.PREFIX+"/schedule_create.html";
    }

    /**
     * 跳转到编辑页面
     * @param scheduleId
     * @param model
     * @return
     */

    @RequestMapping("/edit")
    public String edit(@RequestParam Long scheduleId,Model model){
        if (ToolUtil.isEmpty(scheduleId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("scheduleId", scheduleId);
        return  this.PREFIX+"/schedule_edit.html";
    }

    /**
     * 跳转到合成日程界面
     */
    @RequestMapping("/schedule_copy")
    public String copy(){
        return this.PREFIX+"/schedule_copy.html";
    }

    /**
     * 创建日程
     *
     * @param schedule
     * @return
     */
    @RequestMapping("/schedule_create")
    @ResponseBody
    public ResponseData scheduleCreate(Schedule schedule){

        LoginUser user =  LoginContextHolder.getContext().getUser();//获取当前登录的用户
        schedule.setUserId(user.getId());//补充字段

        Frame theframe = this.frameService.getById(schedule.getFrameId());//获取该框架
        //判断是否是引用他人框架
        if (!user.getId().equals(theframe.getUserId())){
            theframe.setFrameId(null);
            theframe.setPostStatus("PUBLICNABLE");
            theframe.setUserId(user.getId());
            this.frameService.save(theframe);
            Collection<Frameitem> theframeitems = this.frameitemService.selectFramitem(schedule.getFrameId());//获取开框架项的信息
            //克隆框架项内容信息
            for(Frameitem frameitem : theframeitems) {
                frameitem.setFrameitemId(null);
                frameitem.setFrameId(theframe.getFrameId());
                frameitem.setCreateUser(user.getId());
                System.out.println("===================="+theframe);
                System.out.println("===================="+frameitem);
                this.frameitemService.save(frameitem);
            }
        }

        //创建日程
        schedule.setFrameId(theframe.getFrameId());
        this.scheduleIndexService.addSchedule(schedule);
        return SUCCESS_TIP;
    }

    /**
     * 获取一个日程详情信息
     * @param scheduleId
     * @return
     */
    @RequestMapping("/getOneScheduleInfo")
    @ResponseBody
    public ResponseData getOneScheduleInfo(@RequestParam Long scheduleId){

        Schedule scheduleInfo =  this.scheduleIndexService.getOnescheduleInfo(scheduleId);
        return ResponseData.success(scheduleInfo);
    }


    /**
     * 编辑日程信息
     *
     * @param schedule
     * @return
     */
    @RequestMapping("/schedule_edit")
    @ResponseBody
    public ResponseData scheduleEdit(Schedule schedule){

        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        //判断当前用户是否有权限修改
        Schedule theschedule = this.scheduleIndexService.getById(schedule.getScheduleId());
        if(!user.getId().equals(theschedule.getUserId())){
            throw new ServiceException(BizExceptionEnum.NO_PERMITION);
        }
        schedule.setUserId(user.getId());
        //更新日程
        this.scheduleIndexService.editSchedule(schedule);
        return SUCCESS_TIP;
    }

    /**
     * 删除日程
     *
     * @param scheduleId
     * @return
     */
    @RequestMapping("/schedule_delete")
    @ResponseBody
    public ResponseData scheduleDelete(@RequestParam Long scheduleId){
        //判断请求是否有误
        if (ToolUtil.isEmpty(scheduleId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        //判断当前用户是否有权限删除
        Schedule theschedule = this.scheduleIndexService.getById(scheduleId);
        if(!user.getId().equals(theschedule.getUserId())){
            throw new ServiceException(BizExceptionEnum.NO_PERMITION);
        }

        Frame theframe = this.frameService.getById(theschedule.getFrameId());//获取当前框架信息
        //判断当前框架是否是公共使用的，是则删除
        if (theframe.getPostStatus().equals("PUBLICNABLE")){
            this.frameService.deleteFrame(theframe.getFrameId());//删除框架
            this.frameitemService.deleteFrameitem(theframe.getFrameId());//删除框架项
        }
        if (theframe.getPostStatus().equals("DELETE")){
            this.frameitemService.deleteFrameitem(theframe.getFrameId());//删除框架项
        }
        this.scheduleIndexService.deleteScheduleByID(scheduleId);//删除日程
        this.scheduleitemService.deleteAllScheduleitem(scheduleId);//删除日程项
        return SUCCESS_TIP;
    }

    /**
     * 获取全部日程
     * @param publicOrprivate：全部状态
     * @param shareOrnotshare：筛选条件
     * @param sortBydefault：默认排序
     * @param nameOrcontent：名称/描述
     * @param timeLimit
     * @return
     */
    @RequestMapping("/schedule_list")
    @ResponseBody
    public Object List(@RequestParam(required = false) String publicOrprivate,
                       @RequestParam(required = false) String shareOrnotshare,
                       @RequestParam(required = false) String sortBydefault,
                       @RequestParam(required = false) String nameOrcontent,
                       @RequestParam(required = false) String timeLimit){

        //拼接查询条件
        String beginTime = "";
        String endTime = "";
        if (ToolUtil.isNotEmpty(timeLimit)) {
            String[] split = timeLimit.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }

        System.out.println("\n\n\n\n\t1"+publicOrprivate+"\t2"+shareOrnotshare+"\t3"+sortBydefault+"\t4"+nameOrcontent+"\t5"+beginTime+"\t6"+endTime);
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Page<Map<String,Object>> schedule =  this.scheduleIndexService.selectSchedule(publicOrprivate, shareOrnotshare, sortBydefault, nameOrcontent, beginTime, endTime, user.getId());
        Page wrapped = new ScheduleWrapper(schedule).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);
    }

    /**
     *创建时日程时
     * 获取已发布的框架
     * @return
     */

    @RequestMapping("/getEnableFrame")
    @ResponseBody
    public ResponseData List(@RequestParam String condition){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();

        Collection<Frame> frames = this.frameService.selectEnableFrame(user.getId(),condition);

        return ResponseData.success(frames) ;
    }

    /**
     * 获取一个日程及其全部日程项信息
     * @param scheduleId
     * @return
     */
    @RequestMapping("/getschedule_and_item")
    @ResponseBody
    public ResponseData getscheduleAll(@RequestParam Long scheduleId){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Schedule schedule = this.scheduleIndexService.selectScheduleAnditemByscheduleId(scheduleId,user.getId());
        return ResponseData.success(schedule);
    }


    /**
     * 获取今日行程
     * @return
     */
    @RequestMapping("/getTodaySchedule")
    @ResponseBody
    public ResponseData getTodaySchedule(){
        //获取当前登录的用户
        LoginUser user =  LoginContextHolder.getContext().getUser();
        Collection<Schedule> schedules = this.scheduleIndexService.getTodayScheduleService(user.getId());
        System.out.println(schedules);
        return ResponseData.success(schedules);
    }

}
